﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Scheduling.Models;
using Scheduling.Models.Interfaces;
using Scheduling.Models.Helpers;


namespace Scheduling.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            //Obviously a hack, should not be in production code. 
            //This autologin makes it so that we do not have to log in
            //Every time we test website functinality. 
#if DEBUG
            if (Session["AutoAuth"] == null)
            {
                Scheduling.Models.Helpers.UserHelper.LoadIntoSession(Scheduling.Models.Helpers.UserHelper.Authenticate("adm", ""));
                Session["AutoAuth"] = true;
            }
#endif
            
            return View();
        }

        [HttpGet]
        public ActionResult PersonalSchedule(string id)
        {
            var bookingList = new List<Booking>();
            var bookingLoader = IoC.Resolve<IBookingLoader>();
            if (UserHelper.IsUserAuthenticated())
            {
                ViewData["nosearch"] = true;
                bookingList = bookingLoader.GetBookingsByUserID(UserHelper.GetAuthenticatedUserID());
            }
            else
            {
                if (id == null) return View(bookingList);
                foreach (var token in id.Split(','))
                {
                    int x = -1;
                    if (int.TryParse(token, out x))
                    {
                        bookingList.AddRange(bookingLoader.GetBookingsByCourseInstanceID(x));
                    }

                }
            }
            return View(SchedulingHelper.SortByStartDate(bookingList));
        }

        public ActionResult Search(string query)
        {
            var courseInstancesLoader = IoC.Resolve<ICourseInstanceLoader>();
            var instances = courseInstancesLoader.GetCourseInstancesByQuery(query, DateTime.Now.Year - 1, DateTime.Now.Year + 1);
            if (instances.Count < 1) return Content("");
            return View(instances);
        }

        public ActionResult CourseList(string id)
        {
            var courseInstances = new List<CourseInstance>();
            if (id == null) return View(courseInstances);

            var courseInstanceLoader = IoC.Resolve<ICourseInstanceLoader>();
            foreach (string s in id.Split(','))
            {
                int x;
                if (int.TryParse(s, out x))
                {
                    courseInstances.Add(courseInstanceLoader.GetCourseInstance(x));
                }
            }

            
            return View(courseInstances);
        }

        public ActionResult Error()
        {
            return View();
        }
    }
}
